<template>
  <div class="my-collect-box">
    <template v-if="totalArticle !== 0">
      <ArticleCard v-for="(article, index) in articles"
                   :article="article"
                   :key="String(index)">
      </ArticleCard>
      <div class="pagination-box">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalArticle"
            background>
        </el-pagination>
      </div>
    </template>
    <h1 v-else style="text-align: center; margin-top: 100px;">你还没有收藏过任何文章</h1>
  </div>
</template>

<script>
import ArticleCard from "@/components/ArticleCard";
import {listCollectArticle} from "@/api/apis";

export default {
  name: "MyCollect",
  components: {
    ArticleCard,
  },
  data(){
    return {
      articles: [],
      currentPage: 1,
      pageSize: 20,
      totalArticle: 1,
    }
  },
  created(){
    const page = this.$route.query.page
    const size = this.$route.query.size
    if (page){
      this.currentPage = parseInt(page)
    }
    if(size){
      this.pageSize = parseInt(size)
    }
    this.handleListArticle();
  },
  methods:{
    handleListArticle(){
      let params = new URLSearchParams()
      params.append('page', this.currentPage)
      params.append('size', this.pageSize)
      listCollectArticle(params).then(response => {
        this.articles = response.results.data
        this.totalArticle = response.count
      }).catch(err => {
        this.$message.error(err.data.message)
      })
    },
    handleSizeChange(size){
      this.pageSize = size
      if (size > this.totalArticle){
        this.currentPage = 1
      }
      this.$router.push({
        name: 'my-article',
        query: {
          page: this.currentPage,
          size: this.pageSize,
        }
      })
      this.handleListArticle()
    },
    handleCurrentChange(page){
      this.currentPage = page
      this.$router.push({
        name: 'my-article',
        query: {
          page: this.currentPage,
          size: this.pageSize,
        }
      })
      this.handleListArticle()
    },
  },
}
</script>

<style scoped>
  .my-collect-box{
    margin-top: 20px;
  }
  @media screen and (max-width: 767px){
    .my-collect-box{
      padding: 0 20px;
    }
  }
  @media screen and (min-width: 768px){
    .my-collect-box{
      padding: 0 200px;
    }
  }
  .pagination-box{
    text-align: center;
    margin: 10px auto;
    background-color: white;
    padding: 10px 0;
  }
</style>
